package com.wang.leetcode;

/**
 * @Author: along
 * @Create: 2021/4/17 12:18
 * @Description:平衡二叉树
 */
public class Sword55 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (!isBalanced(root.left) || !isBalanced(root.right)) {
            return false;
        }
        if (Math.abs(treeDepth(root.right) - treeDepth(root.left)) > 1) {
            return false;
        }
        return true;
    }

    public int treeDepth(TreeNode root) {
        return root == null ? 0 : Math.max(treeDepth(root.left), treeDepth(root.right)) + 1;
    }
}
